package com.huatech.core.controller;

import java.io.IOException;
import java.util.Collection;
import java.util.Map;

import javax.websocket.OnClose;
import javax.websocket.OnError;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;

import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.web.context.ContextLoader;

import com.alibaba.fastjson.JSONObject;
import com.huatech.core.constant.Constant;
import com.huatech.core.service.AbstractComponent;
import com.huatech.core.support.session.SimpleSessionUtil;
import com.huatech.core.support.session.SimpleSession;


@Component
@ServerEndpoint("/appSocket")
public class AppSocket {
	
	@OnOpen
    public void onOpen(Session session) {
        SimpleSessionUtil.put(session);
        System.out.println("【onOpen消息】有新的连接, 总数:"+SimpleSessionUtil.size());
    }
	
	@OnMessage
	public void onMessage(Session session, String message) throws IOException {
		System.out.println("【onMessage消息】");
		boolean created = SimpleSessionUtil.get(session.getId()).createConn(message);
		JSONObject json = JSONObject.parseObject(message);
		if(!created){
			json.put(Constant.RESPONSE_CODE, "601");
			json.put(Constant.RESPONSE_CODE_MSG, "请求参数错误，url为空");
			if(session.isOpen()){
            	session.getBasicRemote().sendText(json.toJSONString());
            }
		}else{
			handler(json, session);
		}
	}
	
	/**
	 * 每2s刷新一次
	 */
	@Scheduled(fixedDelay = 2000)
	public void scheduled(){
		long start = System.currentTimeMillis();
		Collection<SimpleSession> values = SimpleSessionUtil.values();
		for (SimpleSession simpleSession : values) {
			Map<String, String> _params = simpleSession.getParams();
			for (Map.Entry<String, String> param : _params.entrySet()) {
				handler(JSONObject.parseObject(param.getValue()), simpleSession.getSession());
			}
		}
		
		System.out.println("定时刷新耗时:" + (System.currentTimeMillis() - start)+"，socket连接数：" +values.size());
	}
	
	/**
	 * 消息分发处理
	 * @param json
	 */
	private void handler(JSONObject json, Session session){		
		String result = null;
		AbstractComponent component = null;
		switch (json.getString("url")) {
		case URL.KLINE:// K线
			component = (AbstractComponent) ContextLoader.getCurrentWebApplicationContext().getBean("klineComponent");
			break;
		case URL.OPTIONAL:// 自选
			component = (AbstractComponent) ContextLoader.getCurrentWebApplicationContext().getBean("optionalComponent");
			break;
		case URL.STATEINFO:// 交易状态
			component = (AbstractComponent) ContextLoader.getCurrentWebApplicationContext().getBean("stateInfoComponent");
			break;
		default:
			break;
		}
		if(component != null){
			result = component.handler(json);
		}
		if(result != null && session.isOpen()){
			try {
				session.getBasicRemote().sendText(result);
			} catch (IOException e) {
				System.out.println(e.getMessage());
			}
		}
	}
	
    @OnClose
    public void onClose(Session session) {
    	try {
    		SimpleSessionUtil.remove(session.getId());
			session.close();
		} catch (IOException e) {
		}
    	System.out.println("【onClose消息】连接断开, 总数:"+ SimpleSessionUtil.size());
    }
    
    @OnError
    public void onError(Throwable error) {
    	System.out.println("【onError消息】客户端异常关闭！");
    }
    
    /**
     * 请求url
     * @author lh@erongdu.com
     * @since 2019年3月15日
     * @version 1.0
     *
     */
    public interface URL{
    	String OPTIONAL = "Optional";//自选
    	String KLINE = "Kline";//K线
    	String STATEINFO = "StateInfo";//交易状态    	
    }
	
}
